package com.concurrent.chenjun.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 让线程异常正确的被main捕获
 * @author Administrator
 *
 */
public class ExceptionThread2 implements Runnable
{

	public static void main(String[] args)
	{
		ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
		exec.execute(new ExceptionThread2());
		
	}

	@Override
	public void run()
	{
		Thread t = Thread.currentThread();
		System.out.println("run() by....." + t);
		System.out.println("exceptionHandler = " + t.getUncaughtExceptionHandler());
		throw new RuntimeException("");
	}

}

class MyUncaughExceptionHandler implements Thread.UncaughtExceptionHandler
{

	@Override
	public void uncaughtException(Thread t, Throwable e)
	{
		System.out.println("caught  " + e);
	}

}

class HandlerThreadFactory implements ThreadFactory
{

	@Override
	public Thread newThread(Runnable r)
	{
		System.out.println("HandlerThreadFactory -> newThread()");
		Thread t = new Thread(r);
		System.out.println("create Thread By Runnable r");
		t.setUncaughtExceptionHandler(new MyUncaughExceptionHandler());
		System.out.println("set t.th = MyUncaughExceptionHandler");
		return null;
	}

}
